package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.BrewLab;
import Models.BrewLabDetails;

public class BrewLabPresenter extends AbstractPresenter<BrewLab> {
	final String SINGLEITEM = "brewLab";
	final String MULTIITEM = "brewLabs";
	
	public ArrayList<BrewLab> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public BrewLab tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public BrewLab createItemFromJSONObject(JSONObject jsonObject){
		BrewLab item = new BrewLab();
		try{
			item.setComplete(jsonObject.getBoolean("blComplete"));
			item.setDescription(jsonObject.getString("bldesc"));
			item.setId(jsonObject.getInt("blid"));
			item.setNotes(jsonObject.getString("blNotes"));
			
			BrewViewPresenter bvPresenter = new BrewViewPresenter();
			JSONObject jsonFGI = jsonObject.getJSONObject("brews");
			item.setBrew(bvPresenter.createItemFromJSONObject(jsonFGI));
			
			//Set LabType Collection
			ArrayList<BrewLabDetails> blds = new ArrayList<BrewLabDetails>();
			if(!jsonObject.isNull("brewLabDetailsCollection")){
				Object itm = jsonObject.get("brewLabDetailsCollection");
				BrewLabDetailsPresenter presenter = new BrewLabDetailsPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						blds.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					blds.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setBrewLabDetailCollection(blds);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(BrewLab item){
		try{
			JSONObject json = new JSONObject();
			json.put("blComplete", item.isComplete());
			json.put("bldesc", item.getDescription());
			json.put("blid", item.getId());
			json.put("blNotes", item.getNotes());
			
			BrewViewPresenter bvPresenter = new BrewViewPresenter();
			json.put("brews", bvPresenter.createJSON(item.getBrew()));
			
			//Create Beers Collection
			if(item.getBrewLabDetailCollection()!=null){
				BrewLabDetailsPresenter presenter = new BrewLabDetailsPresenter();
				if(item.getBrewLabDetailCollection().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getBrewLabDetailCollection().size(); i++){
						jsonArray.put(presenter.createJSON(item.getBrewLabDetailCollection().get(i)));
					}
					json.put("brewLabDetailsCollection", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public BrewLab getEmptyEntity(){
		BrewLab entity = new BrewLab();
		return entity;
	}
}
